#!/bin/bash

MY_VERSION=8.0.31
MY_PREFIX=/opt/mysql

MY_TARBALL=${MY_PREFIX}/mysql-${MY_VERSION}-linux-glibc2.17-x86_64-minimal.tar.xz
MY_REALDIR=${MY_PREFIX}/mysql-${MY_VERSION}-linux-glibc2.17-x86_64-minimal
MY_LINKDIR=${MY_PREFIX}/mysql80
MY_BASEDIR=${MY_PREFIX}/mysql
MY_DATADIR=${MY_PREFIX}/data
MY_BINDIR=${MY_BASEDIR}/bin
INST_PKGS=("libaio" "numactl-libs" "openssl")

for PKG in ${INST_PKGS[@]}; do
    if ( ! rpm -q --quiet ${PKG} ); then
        yum install -y ${PKG}
    fi
done

if ( ! getent group mysql 2>&1 >/dev/null ); then
    groupadd mysql
fi
if ( ! getent passwd mysql 2>&1 >/dev/null ); then
    useradd -r -g mysql -s /bin/false mysql
fi
if ( systemctl status -q mysqld.service 2>&1 >/dev/null ); then
    systemctl stop mysqld.service
fi

if [[ ! -d "${MY_REALDIR}" ]]; then
    tar -axvf ${MY_TARBALL} -C ${MY_PREFIX}/
fi
ln -sfT ${MY_REALDIR} ${MY_LINKDIR}
ln -sfT ${MY_LINKDIR} ${MY_BASEDIR}

mkdir -p ${MY_DATADIR}
chown -R mysql:mysql ${MY_DATADIR}
chmod -R 750 ${MY_DATADIR}

if [[ ! -f "${MY_DATADIR}/auto.cnf" ]]; then
    ${MY_BINDIR}/mysqld --initialize --user=mysql --basedir=${MY_BASEDIR} --datadir=${MY_DATADIR}
    ${MY_BINDIR}/mysql_ssl_rsa_setup --uid=mysql --datadir=${MY_DATADIR}
fi

cat > /etc/systemd/system/mysqld.service << EOF
[Unit]
Description=MySQL database server
After=syslog.target
After=network.target

[Service]
Type=simple
User=root
Group=root

ExecStart=${MY_BINDIR}/mysqld_safe --basedir=${MY_BASEDIR} --datadir=${MY_DATADIR}

# Give a reasonable amount of time for the server to start up/shut down
TimeoutSec=300

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl restart mysqld.service

cat > /etc/profile.d/mysql.sh << EOF
#!/bin/bash
export PATH=\${PATH}:${MY_BINDIR}
EOF
